package cn.kimming.rpc.remoting.client;

import cn.kimming.rpc.common.exception.RpcException;
import cn.kimming.rpc.remoting.transport.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientHandler extends SimpleChannelInboundHandler<RpcResponse> {
    private static final Logger logger = LoggerFactory.getLogger(ClientHandler.class);

    private RpcResponse response;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception {
        this.response = response;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.close();
        logger.info("[my-rpc] request: {}, 请求结束, 关闭channel", response.getRequestId());
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        response = new RpcResponse();
        response.setRequestId(response.getRequestId());
        response.setSuccess(false);
        response.setError(new RpcException("客户端发送异常", cause));
        cause.printStackTrace();
        if (cause instanceof ReadTimeoutException) {
            response.setError(new RpcException("服务调用超时", cause));
            logger.error("request: {} calle timen out", response.getRequestId());
        }
        ctx.close();
    }

    public RpcResponse getResponse() {
        return response;
    }
}
